package com.rskj.cashbook.Interceptor;

import com.alibaba.fastjson2.JSON;
import com.rskj.cashbook.response.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.Authentication;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class AuthenticationFilter implements Filter {

    private static final List<String> WHITELIST = Arrays.asList("/user/login", "/user/register", "/error", "user/up/passwd");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;

        String requestURI = httpServletRequest.getRequestURI();

        if (WHITELIST.stream().anyMatch(requestURI::contains)) {
            filterChain.doFilter(httpServletRequest, httpResponse);
            return;
        }

        if (authentication == null || !authentication.isAuthenticated()) {
            httpResponse.setCharacterEncoding("UTF-8");
            httpResponse.setContentType("application/json;charset=UTF-8");
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            httpResponse.getWriter().write(JSON.toJSONString(new ResponseEntity<>()
                    .setCode(401)
                    .setMessage("unAuthenticated")));
            return;
        }

        filterChain.doFilter(httpServletRequest, httpResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
